package com.hongshan.wallet.http

import com.hongshan.wallet.Constant
import com.hongshan.wallet.MyApplication
import com.hongshan.wallet.log
import com.hongshan.wallet.router.RouterIndex
import com.hongshan.wallet.router.go
import com.hongshan.wallet.toast
import okhttp3.Interceptor
import okhttp3.Response
import java.nio.charset.Charset

/**
 * Copyright Qiandai Ltd.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.util
 * @author   : Administrator
 * @data     : 2019/3/18
 * @email    : zhangxx@baihang-china.com
 */
object HttpInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response? {
        return try {
            var request = chain.request()
            if (MyApplication.user?.token != null) {
                log("add token: ${MyApplication.user?.token}")
                request = request.newBuilder().addHeader("token", MyApplication.user?.token!!).build()
            }
            val response = chain.proceed(request)
            if (!response.isSuccessful) {
                return netFail()
            }
            val source = response.body()?.source()
            source?.request(Long.MAX_VALUE)
            val string = source?.buffer()?.clone()?.readString(Charset.forName("UTF-8"))
            checkToken(string)
            response
        } catch (e: Exception) {
            e.printStackTrace()
            return netFail()
        }
    }

    private fun netFail(): Nothing? {
        toast("网络连接异常")
        return null
    }

    fun checkToken(string: String?) {
        val httpResult = Constant.gson.fromJson(string, HttpResult::class.java)
        if (httpResult != null) {
            when (httpResult.code) {
                43001,43002,43004,43005,-4001 -> {
                    toast("登录失效,请重新登录")
                    MyApplication.user?.clean()
                    go(RouterIndex.LOGIN)
                }
                -1 -> {
                    toast(httpResult.msg)
                }
            }
        }
    }
}